﻿var ol_inf_lt = {
  account_info: '/account/queryAccountDetail', //账号信息
  spilt_od_lt: '/order/online/queryByPage',  //线上订单(已/未分单)分页列表
  child_od_lt: '/order/online/querySubByPage',//子订单列表
  company_lt: '/basedata/company/queryCompanyList', //公司列表
  sv_lt: '/basedata/erpServiceClass/queryKVList',// 顶层-服务列表
  dele_od: '/order/online/delete',//删除线上订单
  dispatch_od: '/order/online/distribute',//线上订单分发分单
  ol_od_dt: '/order/online/detail',// 线上订单明细
  build_case: '/orderClient/filing',//立案
  spilt_od: '/order/online/distribute', //分单接口
  cancel_spilt_od: '/order/online/cancle/distribute', //取消分单接口
  file_upload: '/common/file/upload',//上传文件
  acpt_od: '/order/online/confirm/receive',//接单
  agree_cancel: '/order/online/agree/cancle',//同意取消
  delet_ol_od: '/order/online/delete', //删除线上订单
}

var customers = [];

$(function () {
  // wzERP.Contract.init();
  // wzERP.Contract.turnPage();//分页
  wzERP.Common.inlineDate('#date1', '#date2');  //联动日期
});

//渲染搜索客户
$('#customerContent-1').on('keyup', function () {
  $.get('/customer/queryKVList', function (data) {
    console.log(data.data)
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
    }
    var content = []
    var description = []
    for (var i = 0; i < data.data.length; i++) {
      content.push({title: data.data[i].value})
    }
    console.log(description)
    $('#customerSearch-1').search({
      source: content,
    })
  })
})
$('#customerContent-2').on('keyup', function () {
  $.get('/customer/queryKVList', function (data) {
    console.log(data.data)
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
    }
    var content = []
    var description = []
    for (var i = 0; i < data.data.length; i++) {
      content.push({title: data.data[i].value})
    }
    console.log(description)
    $('#customerSearch-2').search({
      source: content,
    })
  })
})
$('#customerContent-3').on('keyup', function () {
  $.get('/customer/queryKVList', function (data) {
    console.log(data.data)
    if (data.code == 9999) {
      // debugger
      layer.msg(data.msg, {time: 1000});
      wzERP.Common.TimeoutLogin();
    }
    var content = []
    var description = []
    for (var i = 0; i < data.data.length; i++) {
      content.push({title: data.data[i].value})
    }
    customers = data.data;
    $('#customerSearch-3').search({
      source: content,
    })
  })
})

var online = {
  init: function () {
    var self = this;
    self.dataInit();
    self.uiInit();//UI-Unit Init
    self.tabInit();
    self.bindEv();
  },
  dataInit: function () {
    var self = this;
    self.accountInfo = {};
    self.hasAccountInfo = false;
  },
  // 删除子订单订单
  cd_od_delet: function (_this) {
    layer.alert('确定删除该子订单吗？', {
          title: '提示信息',
          btn: ['取消', '确认'],
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            var self = this;
            var _url = ol_inf_lt.delet_ol_od;
            var _param = {
              id: _this.parent().data('id'),
            };
            var succ = function (res) {
              if (res.code == 0) {
                _this.parents('tr').remove();
              }
              else if (res.code == 9999) {
                // debugger
                layer.msg(res.msg, {time: 1000});
                wzERP.Common.TimeoutLogin();
              }
              else {
                layer.msg(res.msg, {time: 1000});
              }
            }
            commonFunc.ajax_get(_url, _param, succ,
                {type: 'POST', contentType: 'application/x-www-form-urlencoded'});
          }
        }
    );

    /*layer.confirm('是否删除该子订单？', {
     btn: ['确定', '取消'] //可以无限个按钮
     }, function(index, layero){
     var self = this;
     var _url = ol_inf_lt.delet_ol_od;
     var _param = {
     id: _this.parent().data('id'),
     };
     // _param = JSON.stringify(_param);
     var succ = function(res){
     if(res.code == 0){
     _this.remove();
     }else{
     layer.msg(res.msg,{time: 1000});
     }
     }
     commonFunc.ajax_get(_url,_param,succ,{type: 'POST', contentType: 'application/x-www-form-urlencoded'});
     }, function(index){
     layer.close(index)
     });*/
  },
  od_split_evbind: function (odType) {
    var self = this;
    //切页
    $('select[name="odlt_num"]').on('change', function () {
      var _type = $(this).data('type');
      _type != 2 ? self.spilt_odlt_get(_type, 1) : self.child_odlt_get(_type,
          1);
    });
    //立案
    $('.odlt_table_area').eq(odType).find('.case_build_btn').on('click',
        function () {
          case_build.pop({
            user_nickname: self.accountInfo.employName, //立案人
            orderCode: $(this).parent().data('code'),
            _this: $(this),
            url: "/order/online/detail",
            orderType: 1,
          })
        });
    // 删除
    $('.odlt_table_area').eq(odType).find('.cd_od_delet').on('click',
        function () {
          var _this = $(this);
          self.cd_od_delet(_this);
        });
    // 子订单同意取消
    $('.odlt_table_area').eq(odType).find('.odsp_cencel_enbtn').on('click',
        function () {
          var _this = $(this);
          self.odsp_cencel_ensure(_this);
        });
    // 子订单 接单
    $('.odlt_table_area').eq(odType).find('.od_child_acpt').on('click',
        function () {
          var _id = $(this).parent().data('id');
          var _this = $(this);
          self.od_acpt_dt_get(_id, false, _this);
        });
    // 订单详情 btn
    $('.odlt_table_area').eq(odType).find('.od_dt_btn').on('click',
        function () {
          // var orderCode = $(this).parent().data('code');
          var id = $(this).parent().data('id');
          odType != 2 ? self.od_datail_get(id) : self.od_acpt_dt_get(id, true);
        });
    // 分单 btn
    $('.odlt_table_area').eq(odType).find('.split_od').on('click', function () {
      var _this = $(this);
      $('#od_split_dialog').modal({
        closable: false,
        transition: 'fade',
        onApprove: function () {
          if ($('#od_split_dialog select[name="company_selc"]').val() == '') {
            layer.msg('请选择接单公司！', {time: 1000});
            return false;
          }
          self.od_split_submit(_this, false);
          // return false;
        },
        onHidden: function () {
        }
      }).modal('show');
    });
    // 取消分单 btn
    $('.odlt_table_area').eq(odType).find('.cancel_split_od').on('click',
        function () {
          var _this = $(this);
          var cstCode = _this.parent().data('cst');
          //0已接单1未接单
          cstCode == 0 ? $('#cancel_split_od').modal({
            closable: false,
            transition: 'fade',
            onApprove: function () {
              if ($('#cancel_split_od').find('textarea').val() == '') {
                layer.msg('请填写取消原因', {time: 1000});
                return false;
              }
              ;
              self.od_split_cancel(_this, true);
              return false;
            },
            onHidden: function () {
              $('#cancel_split_od').find('.od_remark').val('');
            }
          }).modal('show') : layer.alert('确定取消分单吗？', {
            title: '提示信息',
            btn: ['取消', '确认'],
            btn1: function (index) {
              layer.close(index)
            },
            btn2: function () {
              self.od_split_cancel(_this);
            }
          });
        })
    // 全选
    $('.od_unit_all').on('click', function () {
      if ($(this).is(':checked')) {
        $(this).parents('table').find('.od_unit:not(:disabled)').prop('checked',
            true);
      } else {
        $(this).parents('table').find('.od_unit:not(:disabled)').prop('checked',
            false);
      }
    })
    $('.od_unit').on('click', function () {
      if ($('.od_unit:checked').length == $('.od_unit').length) {
        $('.od_unit_all').prop('checked', true);
      } else {
        $('.od_unit_all').prop('checked', false);
      }
    })
  },
  //同意取消
  odsp_cencel_ensure: function (_this) {
    var self = this;
    $('#odsp_cencel_ensure .odsp_cencel_ensure_note').html(_this.data('cnote'));
    $('#odsp_cencel_ensure').modal({
      closable: false,
      transition: 'fade',
      onHidden: function () {
        $('.cencel_ensure_selc option').eq(0).prop('selected', 'selected');
      }
    }).modal('show');
    $('#odsp_cencel_ensure .cencel_ensure_submit_btn').off('click').on('click',
        function () {
          if ($('#odsp_cencel_ensure .cencel_ensure_selc').val() == '') {
            layer.msg('请选择同意或是不同意', {time: 1000});
            return;
          }
          self.agree_cencel_submit(_this);
        });
  },
  agree_cencel_submit: function (_this) {
    var self = this;
    var _url = ol_inf_lt.agree_cancel;
    var _param = {
      // id: _this.parent().data('id'),
      agree: $('.cencel_ensure_selc').val(),
      orderCode: _this.parent().data('code'),
    };
    var succ = function (res) {
      if (res.code == 0) {
        _this.addClass('zy_hide');
        $('#odsp_cencel_ensure').modal('hide');
        if (_param.agree == 1) {
          _this.parents('td').find('.cd_od_delet').removeClass('zy_hide');
        } else {
          _this.parents('td').find('.case_build_btn').removeClass('zy_hide');
          _this.parents('td').prev().text('已接单');
        }
        self.refreshPage();
      }
      else if (res.code == 9999) {
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ,
        {type: 'POST', contentType: 'application/x-www-form-urlencoded'});
  },
  // 接单
  od_acpt_submit: function (_this) {
    var self = this;
    var _url = ol_inf_lt.acpt_od;
    var _param = {
      orderCode: _this.parent().data('code'),
      agree: $('select[name="acpt_od_check"]').val(),
      mark: $('textarea[name="acpt_od_remark"]').val(),
    };
    _param = JSON.stringify(_param);
    var succ = function (res) {
      if (res.code == 0) {
        $('#od_acpt_cont_dlg').modal('hide');
        if (_param.agree == 1) {
          _this.addClass('zy_hide').next().removeClass('zy_hide');
          _this.parent().prev().text('已接单');
        } else {
          _this.addClass('zy_hide').parent().find('.cd_od_delet').removeClass(
              'zy_hide');
          _this.parent().prev().text('已取消');
        }
        layer.msg(res.msg, {time: 2000});
        // wzERP.Common.delayReload(wzERP.delayTime);
        self.refreshPage(); //刷新页面
      }
      else if (res.code == 9999) {
        // debugger
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ, {type: 'POST'});
  },
  // 接单/子订单详情 操作
  od_acpt_dt_get: function (id, isDetail, _this) {
    var self = this;
    var _url = ol_inf_lt.ol_od_dt;
    var _param = {
      id: id
    };
    var succ = function (res) {
      if (res.code == 0) {
        // console.log(res)
        isDetail ? function () {
          var _html = template('cd_od_detail_lt_mod', res.data);
          $('#od_detail_cont').html(_html);
          $('#cd_order_dt_dlg').modal({
            closable: false,
            transition: 'fade'
          }).modal('show');
          var numObj = $("[id^='numberD']"),
              totalObj = $("#numberTD"),
              num = 0,
              total = 0;
          numObj.each(function (i, obj) {
            num = parseInt($(obj).html(), 10);
            total += num;
          });
          totalObj.html(total);
        }() : function () {
          var _html = template('od_acpt_cont_mod', res.data);
          $('#od_acpt_cont').html(_html);
          $('#od_acpt_cont_dlg .acpt_od_submit').off('click').on('click',
              function () {
                if ($('#od_acpt_cont_dlg').find(
                        'select[name="acpt_od_check"]').val() == '') {
                  layer.msg('请选择审核结果！', {time: 1000});
                  return false;
                }
                self.od_acpt_submit(_this);
              })
          $('#od_acpt_cont_dlg').modal({
            closable: false,
            transition: 'fade'
          }).modal('show');
          var numObj = $("[id^='numberS']"),
              totalObj = $("#numberTS"),
              num = 0,
              total = 0;
          numObj.each(function (i, obj) {
            num = parseInt($(obj).html(), 10);
            total += num;
          });
          totalObj.html(total);
        }()
      }
      else if (res.code == 9999) {
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ);
  },
  // 订单详情获取
  od_datail_get: function (id) {
    var self = this;
    var _url = ol_inf_lt.ol_od_dt;
    var _param = {
      id: id
    };
    var succ = function (res) {
      if (res.code == 0) {
        console.log(res)
        var _html = template('od_detail_lt_mod', res.data);
        $('#od_detail_lt').html(_html);
        $('#order_dt_dlg').modal({
          closable: false,
          transition: 'fade'
        }).modal('show');

        var numObj = $("[id^='numberN']"),
            totalObj = $("#numberTN"),
            num = 0,
            total = 0;
        numObj.each(function (i, obj) {
          num = parseInt($(obj).html(), 10);
          total += num;
        });
        totalObj.html(total);

      }
      else if (res.code == 9999) {
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ);
  },
  // 事件绑定
  bindEv: function () {
    var self = this;

    $('.check_od_btn').on('click', function () {
      var _type = $(this).data('type');
      _type != 2 ? self.spilt_odlt_get(_type, 1) : self.child_odlt_get(_type,
          1);

    });
    $('.split_odgrp').on('click', function () {
      if ($('.od_unit:checked').length == 0) {
        layer.msg('请选择订单！', {time: 1000});
        return false;
      }
      $('#od_split_dialog').modal({
        transition: 'fade',
        closable: false,
        onApprove: function () {
          if ($('#od_split_dialog select[name="company_selc"]').val() == '') {
            layer.msg('请选择接单公司！', {time: 1000});
            return false;
          }
          self.od_split_submit('', true);
          // return false;
        },
        onHidden: function () {
          self.od_split_dlg_init();
        }
      }).modal('show');
    });
  },
  //finished Content
  // 页面初始化部分
  uiInit: function () {
    var self = this;
    $('.olod_tab .item').tab({
      onFirstLoad: function () {

      },
      onLoad: function () {
        // $('.ol_tab').eq(0).addClass('loading');
        self.tabContCtrler(1); //tab-content get
      }
    });
    wzERP.Common.inlineDate('.ol_date1_on', '.ol_date2_on');//联动日期

    $("#w_city").citypicker();//城市控件初始化
    $("#f_city").citypicker();
    $("#cd_city").citypicker();

    components.svLtGet($('select[name="escID"]')); // 服务分类获取
    components.company_lt_get($('.company_selc')); // 获取公司列表
  },

  // 取消分单接口
  od_split_cancel: function (act_el, hasAcpt) {
    var self = this;
    var _url = ol_inf_lt.cancel_spilt_od;
    var _param = {
      did: act_el.parent().data('did'),
      cancelStatus: act_el.parent().data('cst'),
    };
    hasAcpt = hasAcpt != undefined ? hasAcpt : false;
    if (hasAcpt) {
      _param.mark = $('#cancel_split_od').find('textarea').val();
    }
    var succ = function (res) {
      if (res.code == 0) {
        layer.msg(res.msg, {time: 3000});
        act_el.parent().data('cst') == 0 ? act_el.remove() : act_el.parents(
            'tr').remove();
        if (hasAcpt) {
          $('#cancel_split_od').modal('hide');
          $('#cancel_split_od').find('.od_remark').val('');
        }
      }
      else if (res.code == 9999) {
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ,
        {type: 'POST', contentType: 'application/x-www-form-urlencoded'});
  },
  // 页码条初始化
  paginationInit: function (odType) {
    var self = this;
    layui.laypage({
      cont: 'page_num' + odType,
      pages: $('#page_num' + odType).data('amount'),
      skin: '#1E9FFF',
      curr: $('#page_num' + odType).data('curr'),
      groups: 4,
      skip: true,
      prev: false,
      next: false,
      jump: function (obj, first) {
        if (!first) {
          odType != 2 ? self.spilt_odlt_get(odType, obj.curr)
              : self.child_odlt_get(odType, obj.curr);
        }
      },
    });
  },
  //获取子订单
  child_odlt_get: function (odType, currPage) {
    var self = this;
    $('.ol_tab').eq(0).addClass('loading');
    var _url = ol_inf_lt.child_od_lt;
    var _param = self.child_od_ck_pm(odType, currPage);
    var succ = function (res) {
      if (res.code == 0) {
        console.log(res);
        res.data.od_type = odType;
        var _html = template('child_od', res.data);
        $('.odlt_table_area').eq(odType).html(_html);
        self.paginationInit(odType);  //页码init
        self.od_split_evbind(odType);
        $('.ui.dropdown').dropdown();//dropdown 下拉
        $('.ol_tab').eq(0).removeClass('loading');
      }
      else if (res.code == 9999) {
        // debugger
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
      permissonHandler();
    }
    commonFunc.ajax_get(_url, _param, succ);
  },
  child_od_ck_pm: function (odType, currPage) {
    var self = this;
    var _el = $('.ol_tab').eq(odType).find('.srh_section');
    var _odlt_num = $('.ol_tab').eq(odType).find(
        'select[name="odlt_num"]').val();
    // _odlt_num = _odlt_num==''?10: _odlt_num;
    var _formData = commonFunc.serializeToObj(_el.find('form').serialize());
    var custId;
    if(_formData.searchKey != ""){
        for(var i=0; i< customers.length; i++){
            if(encodeURI(customers[i].value) == _formData.searchKey){
                custId = customers[i].key
            }
        }
    }
    if(custId){
        _formData.custId = custId
    }
    var _param = {
      current: currPage,
      pageSize: _odlt_num == '' ? 10 : _odlt_num,
    }
    _param = $.extend(_param, _formData);
    return _param;
  },
  // tab初始化
  tabInit: function () {
    var self = this;
    self.accountInfo_get(); //状态检测
    if (!self.hasAccountInfo) {
      return;
    }
    // tab-init change
    if (!(self.accountInfo.companyCode == '013')) {
      $('.olod_tab .item').eq(2).removeClass('zy_hide').css({
        position: 'relative',
        top: '1px',
      }).click();
    } else {
      $('.olod_tab .item').removeClass('zy_hide')
    }
    // $('.ol_tab').eq(0).addClass('loading');
    self.tabContCtrler(1);
    // sercher-section data get
    // self.svLtGet(); //service-list-get
  },
  // tab-initPage Ctrler
  tabContCtrler: function (pageSort) {
    var self = this;
    var odType = $('.olod_tab .item.active').data('sort');
    $('.olod_tab .item.active').data('sort') == 2 ? self.child_odlt_get(odType,
        pageSort) : self.spilt_odlt_get(odType, pageSort);
  },
  // 分单分页数据获取
  spilt_odlt_get: function (odType, currPage) {
    var self = this;
    $('.ol_tab').eq(0).addClass('loading');
    var _url = ol_inf_lt.spilt_od_lt;
    var _param = self.spilt_od_ck_pm(odType, currPage);
    var succ = function (res) {
      if (res.code == 0) {
        res.data.od_type = odType;
        var _html = template('split_od', res.data);
        $('.odlt_table_area').eq(odType).html(_html);
        self.paginationInit(odType);  //页码init
        self.od_split_evbind(odType); //table-btn event
        $('.ui.dropdown').dropdown();//dropdown 下拉
        $('.ol_tab').eq(0).removeClass('loading');
      }
      else if (res.code == 9999) {
        // debugger
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
      permissonHandler();
    }
    commonFunc.ajax_get(_url, _param, succ);
  },
  spilt_od_ck_pm: function (odType, currPage) {
    var self = this;
    var _el = $('.ol_tab').eq(odType).find('.srh_section');
    var spcode = $('.olod_tab .item').eq(odType).data('spcode');
    var _regionCodeEl = _el.find('.region_selc .select-item');
    var _odlt_num = $('.ol_tab').eq(odType).find(
        'select[name="odlt_num"]').val();
    var _formData = commonFunc.serializeToObj(_el.find('form').serialize());
    var _param = {
      custName: _el.find('.cust_name').val(),
      separateStatus: spcode,//odType //分单状态 0未分单，1：已分单
      provinceCode: _regionCodeEl.eq(0).data('code'),//省编码
      cityCode: _regionCodeEl.eq(1).data('code'),//市编码
      countyCode: _regionCodeEl.eq(2).data('code'),//县编码
      current: currPage,//当前页码
      pageSize: _odlt_num == '' || _odlt_num == undefined ? 10 : _odlt_num,//每页显示数量
    }
    _param = $.extend(_param, _formData);
    return _param;
  },
  //分单
  od_split_dlg_init: function () {
    var _el = $('#od_split_dialog');
    _el.find('.company_selc option').eq(0).prop('selected', true);
    _el.find('.od_remark').val('');
  },
  od_split_param: function (_this, isAllSelc) {
    var _param = {
      receiveCompanyCode: $('.company_selc').val(), //接单公司编号
      descript: $('#od_split_dialog .od_remark').val(),//描述
      skuList: [],
    }
    if (!isAllSelc) {
      _param.skuList = [{
        orderCode: _this.parent().data('code'),
        did: _this.parent().data('did'),
      }]
    } else {
      $('.od_unit:checked').each(function () {
        _param.skuList.push({
          orderCode: $(this).data('code'),
          did: $(this).val(),
        })
      })
    }
    return JSON.stringify(_param);
  },
  od_split_submit: function (_this, isAllSelc) {
    var self = this;
    var _url = ol_inf_lt.spilt_od;
    var _param = self.od_split_param(_this, isAllSelc);
    var succ = function (res) {
      if (res.code == 0) {
        if (!isAllSelc) {
          _this.parents('tr').remove();
        } else {
          $('.od_unit:checked').parents('tr').remove();
        }
        $('#od_split_dialog').modal('hide');
        self.od_split_dlg_init();
      }
      else if (res.code == 9999) {
        // debugger
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg(res.msg, {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ, {type: 'POST'});
    // NetUtis.doPostBodySimple(_url,_param,function (data) {
    //     console.log(data);
    // });
  },
  //account info get
  accountInfo_get: function () {
    var self = this;
    var _url = ol_inf_lt.account_info;
    var _param = {};
    var succ = function (res) {
      if (res.code == 0) {
        self.accountInfo = res.data;
        self.hasAccountInfo = true;
        // console.log(self.accountInfo)
      }
      else if (res.code == 9999) {
        layer.msg(res.msg, {time: 1000});
        wzERP.Common.TimeoutLogin();
      }
      else {
        layer.msg('账号信息获取失败，请刷新页面重新加载', {time: 1000});
      }
    }
    commonFunc.ajax_get(_url, _param, succ, {async: false});
  },
  //刷新页面
  refreshPage: function () {
    var self = this;
    // $('.ol_tab.active').find('.check_od_btn').click();
    var odType = $('.olod_tab .item.active').data('sort');
    var pageSort = $('.ol_tab.active').find('.page_change_block').data('curr');
    $('.olod_tab .item.active').data('sort') == 2 ? self.child_odlt_get(odType,
        pageSort) : self.spilt_odlt_get(odType, pageSort);
  }
}
online.init();

